"use server";

import { redirect } from "next/navigation";
import { z } from "zod";

import { validatedAction } from "~/lib/actions";
import { createClient } from "~/lib/supabase/server";

const signInSchema = z.object({
  email: z.string().email({ message: "请输入正确的邮箱格式" }),
  password: z
    .string()
    .min(6, { message: "密码必须为6位以上" })
    .max(64, { message: "密码必须为6位以上" }),
  returnUrl: z.string().optional(),
});

export const signIn = validatedAction(signInSchema, async (data) => {
  const { email, password, returnUrl } = data;

  const supabase = await createClient();

  const { error } = await supabase.auth.signInWithPassword({
    email,
    password,
  });

  if (error) {
    return { error: error.message || "账号或密码错误，请重试。" };
  }

  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  return { success: true, redirectTo: returnUrl || "/" };
});

export async function signOut() {
  const supabase = await createClient();
  const { error } = await supabase.auth.signOut();

  if (error) {
    return { message: error.message || "退出登录失败，请重试。" };
  }

  return redirect("/");
}
